// ignore_for_file: must_be_immutable

import 'package:flutter/material.dart';
import 'package:flutter_basic_library/flutter_basic_library.dart';
import 'package:flutter_basic_library/utils/color_utils.dart';

typedef ExpandCall = Function(bool isExpand);

///自定义的垂直方向的展开和折叠
///标题信息  点击事件 在主体的下面
class CustomExpandCollapseWidget extends StatefulWidget {
  ///要展开组件
  Widget? openChild;

  ///折叠后的组件
  Widget? closeChild;

  ///固定的标题组件  展开的标题组件
  Widget? openTitle;

  ///固定的标题组件 折叠标题组件
  Widget? closeTitle;

  ///展开和折叠的监听
  ExpandCall? expandCall;

  ///设置背景颜色  默认为白色
  Color? bgColor;

  ///默认标题组件的展开描述
  String? defaultOpenTitleDesc;

  ///默认标题组件收起的描述
  String? defaultCloseTitleDesc;

  CustomExpandCollapseWidget(
      {Key? key, required this.openChild, this.closeChild, this.openTitle, this.defaultCloseTitleDesc, this.defaultOpenTitleDesc, this.closeTitle, this.expandCall, this.bgColor})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => CustomExpandCollapseWidgetState();
}

class CustomExpandCollapseWidgetState extends State<CustomExpandCollapseWidget> with TickerProviderStateMixin {
  ///是否展开
  bool? isExpand = false;
  bool offstage = true;

  Animation? animation;
  AnimationController? controller;
  GlobalKey childGlobalKey = GlobalKey();
  GlobalKey childCloseGlobalKey = GlobalKey();
  double? height;
  double? heightClose;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    controller = AnimationController(duration: const Duration(milliseconds: 150), vsync: this);
    Future.delayed(const Duration(milliseconds: 50)).then((e) {
      if (height == null || height == 0) {
        _getWidgetHeight();
      }
      animation = Tween(begin:heightClose, end: height).animate(controller!)
        ..addListener(() {
          if (animation!.status == AnimationStatus.dismissed && animation!.value == heightClose) {
            offstage = !offstage;
          }
          setState(() => {});
        });
    });
  }

  void _getWidgetHeight() {
    final listHeight = childGlobalKey.currentContext!.findRenderObject()!.semanticBounds.size.height;
    heightClose = 0;
    if( widget.closeChild!=null){
      heightClose = childCloseGlobalKey.currentContext!.findRenderObject()!.semanticBounds.size.height;
    }
    if (height == null || height == 0) {
      height = listHeight;
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      color: widget.bgColor ?? Colors.white,
      child: Column(
        children: [
          height == null
              ? Stack(
            children: [
              Container(
                key: childCloseGlobalKey,
                width: double.infinity,
                child: widget.closeChild ?? const SizedBox(),
              ),
              Offstage(
                offstage: true,
                child: Container(key: childGlobalKey, width: double.infinity, child: widget.openChild),
              )
            ],
          )
              : Stack(
            children: [
              Offstage(
                offstage: offstage,
                child: Container(
                  width: double.infinity,
                  height: ((animation?.value ?? height) > height ? height : animation?.value),
                  child: widget.openChild,
                ),
              ),
              Offstage(
                offstage: !offstage,
                child: Container(
                  width: double.infinity,
                  child: widget.closeChild ?? const SizedBox(),
                ),
              )
            ],
          ),
          GestureDetector(
            onTap: () {
              isExpand = !isExpand!;
              widget.expandCall?.call(isExpand!);
              _startAnimtion();
            },
            child: widget.openTitle != null ? _customerTitle() : _defaultTitle(),
          )
        ],
      ),
    );
  }

  ///返回自定义的祖丁组件
  Widget _customerTitle() {
    return Container(
      decoration: BoxDecoration(
          border: Border(
            top: BorderSide(color: ColorUtil(color_f4f4f4)),
          )),
      width: double.infinity,
      alignment: Alignment.center,
      padding: const EdgeInsets.all(10),
      margin: const EdgeInsets.all(10),
      child: offstage ? widget.closeTitle! : widget.openTitle!,
    );
  }

  ///返回默认的标题组件
  Widget _defaultTitle() {
    return Container(
      decoration: BoxDecoration(
          border: Border(
        top: BorderSide(color: ColorUtil(color_f4f4f4)),
      )),
      width: double.infinity,
      alignment: Alignment.center,
      padding: const EdgeInsets.all(10),
      child: Container(
        decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(100)),border: Border.all(color: ColorUtil(color_999999),width: 0.5)),
        padding: const EdgeInsets.only(left: 15, right: 10, top: 2,bottom: 2),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              offstage
                  ? (widget.defaultOpenTitleDesc != null ? widget.defaultOpenTitleDesc! : '展 开 信 息')
                  : (widget.defaultCloseTitleDesc != null ? widget.defaultCloseTitleDesc! : '收 起 信 息'),
              style: TextStyle(color: ColorUtil(color_666666), fontSize: 13.sp),
            ),
            const SizedBox(width: 5,),
            Icon(offstage ? Icons.keyboard_arrow_down : Icons.keyboard_arrow_up,color: ColorUtil(color_999999),size: 20,)
          ],
        ),
      ),
    );
  }

  _startAnimtion() {
    if (isExpand!) {
      //展开
      offstage = !offstage;
      //启动动画(正向执行)
      controller!.forward();
    } else {
      controller!.reverse();
    }
  }

  @override
  void dispose() {
    controller!.dispose();
    super.dispose();
  }
}
